package com.suman.rss.configure;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RemoteViews;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;

import com.suman.bbcticker.R;
import com.suman.rss.Eula;
import com.suman.rss.activity.WrongLaunchAlertActivity;
import com.suman.rss.service.RssReaderService;
import com.suman.rss.widget.SkyNewsReaderAppWidget;

public class RssFeedWidgetConfiguration extends Activity {

	static final String TAG = "RssFeedWidgetConfiguration";

	public static final String PREFS_NAME = "com.suman.rss.widget.SkyNewsReaderAppWidget";
	public static final String PREF_PREFIX_KEY = "prefix_";

	private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
	EditText configureFeedRefreshTimeView;
	Spinner configureFeedAlertTypeView;
	Spinner configureSiteSelectionView;

	final static int ALERTTYPE_NONE = 0;
	final static int ALERTTYPE_SOUND = 1;
	final static int ALERTTYPE_VIBRATE = 2;

	final static int SITE_SKYNEWS = 0;
	final static int SITE_SKYSPORTS = 1;
	final static int SITE_BBCNEWS = 2;
	final static int SITE_FOXNEWS = 3;
	final static int SITE_CNNNEWS = 4;
	final static int SITE_SKYNEWSITALY = 5;

	public RssFeedWidgetConfiguration() {
		super();
	}

	@Override
	public void onCreate(Bundle icicle) {

		super.onCreate(icicle);
		Eula.showEula(this);

		// get any data we were launched with
		Intent launchIntent = getIntent();
		Bundle extras = launchIntent.getExtras();
		if (extras != null) {

			mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);

			Intent cancelResultValue = new Intent();
			cancelResultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
			setResult(RESULT_CANCELED, cancelResultValue);
		} else if (Intent.ACTION_MAIN.equalsIgnoreCase(launchIntent.getAction())
		        && launchIntent.hasCategory(Intent.CATEGORY_LAUNCHER)) {

			Intent intent = new Intent();
			intent.setClass(this, WrongLaunchAlertActivity.class);
			startActivity(intent);
		} else {

			// only launch if it's for configuration
			// Note: when you launch for debugging, this does prevent this
			// activity from running. We could also turn off the intent
			// filtering for main activity.
			// But, to debug this activity, we can also just comment the
			// following line out.
			// TODO need to alert user in a different activity saying that they cant add thuyis
			// widget from
			// Menu but instead need to add it from home screen
			finish();
		}

		// Set the view layout resource to use.
		setContentView(R.layout.widget_configuration);

		configureFeedRefreshTimeView = (EditText) findViewById(R.id.widget_configuration_feedrefresheditbutton);
		configureFeedAlertTypeView = (Spinner) findViewById(R.id.widget_configuration_dropdown);
		configureSiteSelectionView = (Spinner) findViewById(R.id.widget_configuration_siteselection_dropdown);

		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.alerttype,
		        android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		configureFeedAlertTypeView.setAdapter(adapter);
		configureFeedAlertTypeView.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				final Context context = RssFeedWidgetConfiguration.this;
				if (position == ALERTTYPE_NONE) {
					savePreferenceWithLayoutAndAppWidgetId(context, mAppWidgetId, R.id.widget_configuration_dropdown,
					        "ALERTTYPE_NONE");
				} else if (position == ALERTTYPE_SOUND) {
					savePreferenceWithLayoutAndAppWidgetId(context, mAppWidgetId, R.id.widget_configuration_dropdown,
					        "ALERTTYPE_SOUND");
				} else if (position == ALERTTYPE_VIBRATE) {
					savePreferenceWithLayoutAndAppWidgetId(context, mAppWidgetId, R.id.widget_configuration_dropdown,
					        "ALERTTYPE_VIBRATE");
				}
			}

			public void onNothingSelected(AdapterView<?> parent) {
				final Context context = RssFeedWidgetConfiguration.this;
				savePreferenceWithLayoutAndAppWidgetId(context, mAppWidgetId, R.id.widget_configuration_dropdown,
				        "ALERTTYPE_NONE");
			}
		});

		ArrayAdapter<CharSequence> adapterForSiteSelection = ArrayAdapter.createFromResource(this,
		        R.array.newssiteselection, android.R.layout.simple_spinner_item);
		adapterForSiteSelection.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		configureSiteSelectionView.setAdapter(adapterForSiteSelection);
		configureSiteSelectionView.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				final Context context = RssFeedWidgetConfiguration.this;
				if (position == SITE_SKYNEWS) {
					savePreferenceWithLayoutAndAppWidgetId(context, mAppWidgetId,
					        R.id.widget_configuration_siteselection_dropdown, RssReaderService.SITE_SKY_NEWS);
				} else if (position == SITE_SKYSPORTS) {
					savePreferenceWithLayoutAndAppWidgetId(context, mAppWidgetId,
					        R.id.widget_configuration_siteselection_dropdown, RssReaderService.SITE_SKY_SPORTS);
				} else if (position == SITE_BBCNEWS) {
					savePreferenceWithLayoutAndAppWidgetId(context, mAppWidgetId,
					        R.id.widget_configuration_siteselection_dropdown, RssReaderService.SITE_BBC_NEWS);
				} else if (position == SITE_FOXNEWS) {
					savePreferenceWithLayoutAndAppWidgetId(context, mAppWidgetId,
					        R.id.widget_configuration_siteselection_dropdown, RssReaderService.SITE_FOX_NEWS);
				} else if (position == SITE_CNNNEWS) {
					savePreferenceWithLayoutAndAppWidgetId(context, mAppWidgetId,
					        R.id.widget_configuration_siteselection_dropdown, RssReaderService.SITE_CNN_NEWS);
				} else if (position == SITE_SKYNEWSITALY) {
					savePreferenceWithLayoutAndAppWidgetId(context, mAppWidgetId,
					        R.id.widget_configuration_siteselection_dropdown, RssReaderService.SITE_SKY_ITALY);
				}
			}

			public void onNothingSelected(AdapterView<?> parent) {
				final Context context = RssFeedWidgetConfiguration.this;
				savePreferenceWithLayoutAndAppWidgetId(context, mAppWidgetId,
				        R.id.widget_configuration_siteselection_dropdown, RssReaderService.SITE_SKY_NEWS);
			}
		});

		// Bind the action for the save button.
		findViewById(R.id.widget_configuration_savebutton).setOnClickListener(mOnClickListener);

		// If they gave us an intent without the widget id, just bail.
		if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
			finish();
		}

	}

	View.OnClickListener mOnClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			final Context context = RssFeedWidgetConfiguration.this;

			// When the button is clicked, save the string in our prefs and
			// return that they
			// clicked OK.
			String feedRefreshTime = configureFeedRefreshTimeView.getText().toString();
			savePreferenceWithLayoutAndAppWidgetId(context, mAppWidgetId,
			        R.id.widget_configuration_feedrefresheditbutton, feedRefreshTime);

			Intent widgetUpdate = new Intent(context, SkyNewsReaderAppWidget.class);
			widgetUpdate.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { mAppWidgetId });
			widgetUpdate.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
			widgetUpdate.putExtra("unique", "unique");

			// make this pending intent unique
			widgetUpdate.setData(Uri.withAppendedPath(Uri.parse(SkyNewsReaderAppWidget.URI_SCHEME + "://widget/id/"),
			        String.valueOf(mAppWidgetId)));
			PendingIntent newPending = PendingIntent.getBroadcast(getApplicationContext(), 0, widgetUpdate,
			        PendingIntent.FLAG_UPDATE_CURRENT);

			// schedule the new widget for updating
			AlarmManager alarms = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
			int updateRateInMins = Integer.parseInt(feedRefreshTime);
			alarms.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),
			        updateRateInMins * 1000 * 60, newPending);

			// Make sure we pass back the original appWidgetId
			Intent resultValue = new Intent();
			resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);

			setResult(RESULT_OK, resultValue);
			savePreferenceAsString(context, PREF_PREFIX_KEY + mAppWidgetId, "saved");
			updateRemoteViewWithLoadingMessage(context, mAppWidgetId);
		}

		private void updateRemoteViewWithLoadingMessage(Context context, int appWidgetId) {
			RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_word);
			updateViews.setTextViewText(R.id.word_title,
			        "Loading...Trying to connect to network...Please Wait.Thank You For Your Patience.");
			AppWidgetManager manager = AppWidgetManager.getInstance(context);
			manager.updateAppWidget(mAppWidgetId, updateViews);
			finish();
		}

	};

	static void savePreferenceWithLayoutAndAppWidgetId(Context context, int appWidgetId, int layoutWidgetId, String text) {
		savePreferenceAsString(context, PREF_PREFIX_KEY + appWidgetId + layoutWidgetId, text);
	}

	private static void savePreferenceAsString(Context context, String key, String text) {
		SharedPreferences.Editor prefs = context.getSharedPreferences(PREFS_NAME, 0).edit();
		prefs.putString(key, text);
		prefs.commit();
	}

}
